package com.my.biz.service.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.my.api.request.user.LoginRequest;
import com.my.api.request.user.RegisterRequest;
import com.my.api.response.Msg;
import com.my.biz.dao.UserInfoMapper;
import com.my.biz.domain.UserInfoDO;
import com.my.biz.service.ITokenService;
import com.my.biz.service.IUserInfoService;
import com.my.core.base.dao.GenericDao;
import com.my.core.base.service.AbstractGenericService;
import com.my.util.CipherUtil;
import com.my.util.MsgUtil;
import com.my.util.UuidUtil;


 /**
 * 
 * @描述：IUserInfoService 服务实现类
 * 
 * @创建人： ch
 * 
 * @创建时间：2017年07月04日 21:10:39
 * 
 */
@Service("iUserInfoService")
public class UserInfoServiceImpl extends AbstractGenericService<UserInfoDO, Long> implements IUserInfoService{
	
	private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoServiceImpl.class);
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	@Autowired
	private ITokenService tokenService;
	
	@Override
    public GenericDao<UserInfoDO, Long> getDao() {
        return userInfoMapper;
    }

	@Override
	public Msg register(RegisterRequest req) {
		UserInfoDO c = new UserInfoDO(req.getAccount());
		if(selectOne(c) != null){
			return MsgUtil.error("账号已注册");
		}
		String uid = UuidUtil.uuid();
		UserInfoDO reg = new UserInfoDO(uid,req.getAccount(),CipherUtil.generatePassword(req.getPassword()),System.currentTimeMillis()+(86400000*3));
		insert(reg);
		String token = tokenService.creatToken(uid);
		Map<String, Object> map = Maps.newHashMap();
		map.put("token", token);
		return MsgUtil.success(map);
	}

	@Override
	public Msg login(LoginRequest req) {
		UserInfoDO c = new UserInfoDO(req.getAccount(),CipherUtil.generatePassword(req.getPassword()));
		UserInfoDO u = selectOne(c);
		if(u == null){
			return MsgUtil.error("账号或者密码不正确");
		}
		if(u.getAuthExpireTime()>System.currentTimeMillis()){
			return MsgUtil.error("授权过期,请重新授权");
		}
		String token = tokenService.creatToken(u.getUid());
		Map<String, Object> map = Maps.newHashMap();
		map.put("token", token);
		return MsgUtil.success(map);
	}
    


}
